<template>
  <div class="add_operational_people_page">
    <el-form ref="form" :model="form" :rules="rules">
      <div class="mod">
        <div class="title">
          <i class="icon"></i>
          新增运营人员
        </div>
        <div class="content">
          <div class="upload_box">
            <el-form-item prop="contactRPic" :error="contactRPicError" label-width="0">
              <div class="ID_top" v-if="form.contactRPic">
                <img :src="baseURL + form.contactRPic" alt="" class="img" />
                <div class="mask">
                  <i
                    class="el-icon-search preview"
                    @click.stop="previewBigImg(form.contactRPic)"
                  ></i>
                  <i
                    class="el-icon-delete delete"
                    @click.stop="deleteContactRPic"
                  ></i>
                </div>
              </div>
              <div class="ID_top" v-loading="contactRPicLoading" v-else>
                <input
                  type="file"
                  accept="image/jpeg,image/jpg,image/png"
                  name="file"
                  class="upload_input"
                  @change="ocrIdCardFront"
                />
              </div>
            </el-form-item>
            <el-form-item prop="contactBPic" :error="contactBPicError" label-width="0">
              <div class="ID_back" v-if="form.contactBPic">
                <img :src="baseURL + form.contactBPic" alt="" class="img" />
                <div class="mask">
                  <i
                    class="el-icon-search preview"
                    @click.stop="previewBigImg(form.contactBPic)"
                  ></i>
                  <i
                    class="el-icon-delete delete"
                    @click.stop="deleteContactBPic"
                  ></i>
                </div>
              </div>
              <div class="ID_back" v-loading="contactBPicLoading" v-else>
                <input
                  type="file"
                  accept="image/jpeg,image/jpg,image/png"
                  name="file"
                  class="upload_input"
                  @change="ocrIdCardBack"
                />
              </div>
            </el-form-item>
            <div class="desc_box">
              <div class="desc_name">上传说明：</div>
              <div class="desc_text">
                <div>请上传清晰的证件照片</div>
                <div>系统将自动识别证件信息</div>
                <div>文件仅限jpeg/jpg/png格式，且大小不超过10M</div>
              </div>
            </div>
          </div>
          <div class="tips">
            <i class="el-icon-warning icon"></i>
            部分信息由图片自动识别，请仔细核对，如有出入请及时修正
          </div>
          <div class="msg_box">
            <el-row>
              <el-col :span="12">
                <el-form-item label="姓名" prop="contactName">
                  <el-input v-model="form.contactName"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="证件类型" prop="contactType">
                  <el-select
                    v-model="form.contactType"
                    style="width: 100%"
                  >
                    <el-option value="">请选择</el-option>
                    <el-option
                      v-for="item in idTypeList"
                      :key="item.dictValue"
                      :value="item.dictLabel"
                    >{{ item.dictLabel }}</el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="身份证号" prop="contactId">
                  <el-input v-model="form.contactId"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="性别" prop="contactSex">
                  <el-select
                    v-model="form.contactSex"
                    style="width: 100%"
                  >
                    <el-option value="">请选择</el-option>
                    <el-option
                      v-for="item in sexList"
                      :key="item.dictValue"
                      :value="item.dictLabel"
                    >{{ item.dictLabel }}</el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="民族" prop="contactEthnic">
                  <el-input v-model="form.contactEthnic"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="签发机关" prop="contactIssuing">
                  <el-input v-model="form.contactIssuing"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="出生日期" prop="contactBirth">
                  <el-date-picker
                    v-model="form.contactBirth"
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"
                    style="width: 100%"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="证件起始日期" prop="contactCardStart">
                  <el-date-picker
                    v-model="form.contactCardStart"
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"
                    style="width: 100%"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item
                  label="证件到期日期"
                  :prop="form.longEffect === true ? 'longEffect' : 'contactCardEnd'"
                >
                  <div class="long_effect_line">
                    <el-date-picker
                      v-model="form.contactCardEnd"
                      format="yyyy-MM-dd"
                      value-from="yyyy-MM-dd"
                      style="width: 100%"
                      :disabled="form.longEffect === true"
                    ></el-date-picker>
                    <el-checkbox
                      class="long_effect"
                      v-model="form.longEffect"
                      :disabled="form.longEffect === false"
                    >长期有效</el-checkbox>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="户籍地址" prop="contactAddress">
                  <el-input v-model="form.contactAddress"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="手机号码" prop="contactPhone">
                  <el-input v-model="form.contactPhone"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="邮箱" prop="contactEmail">
                  <el-input v-model="form.contactEmail"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="运营人员状态" prop="status">
                  <el-select v-model="form.status" style="width: 100%;">
                    <el-option value="">请选择</el-option>
                    <el-option
                      v-for="item in statusList"
                      :key="item.dictValue"
                      :label="item.dictLabel"
                      :value="item.dictValue"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
      </div>
      <div class="mod">
        <div class="title">
          <i class="icon"></i>
          分配权限
        </div>
        <div class="content">
          <el-row>
            <el-form-item label="数信易链">
              <el-checkbox-group v-model="form.privilegeYl">
                <el-checkbox label="10">初审</el-checkbox>
                <el-checkbox label="20">复审</el-checkbox>
                <el-checkbox label="30">查看</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="数信易融">
              <el-checkbox-group v-model="form.privilegeYr">
                <el-checkbox label="10">初审</el-checkbox>
                <el-checkbox label="20">复审</el-checkbox>
                <el-checkbox label="30">查看</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-row>
        </div>
      </div>
      <div class="mod btns">
        <el-button class="btn btn_cancel" @click="cancelFn">取消</el-button>
        <el-button type="primary" class="btn btn_sure" :loading="submitLoading" @click="submit"
          >确定</el-button
        >
      </div>
    </el-form>
    <CustomDialog
      title="查看内容"
      width="70%"
      :visible="dialogVisible"
      @close="dialogVisible = false"
    >
      <div class="mask_dialog_content">
        <div class="img_box">
          <img :src="baseURL + previewBigImgUrl" alt="" class="img" />
        </div>
      </div>
    </CustomDialog>
  </div>
</template>

<script>
import { operationDetail, addOperation, editOperation } from "@/api/companyManage";
import { uploadImg } from "@/utils/request";
import CustomDialog from '@/customComponents/dialog'

export default {
  components: {
    CustomDialog,
  },
  data() {
    return {
      baseURL: process.env.NODE_ENV === 'development' ? process.env.VUE_APP_BASE_API :
        process.env.VUE_APP_HTTP_REQUEST_ADDRESS,
      idTypeList: [], // 身份证类型列表
      sexList: [], // 性别列表
      statusList: [], // 运营人员状态列表
      contactRPicLoading: false,
      contactBPicLoading: false,
      submitLoading: false,
      form: {
        contactName: '', // '联系人姓名',
        contactType: '', // '证件类型',
        contactId: '', // '身份证号',
        contactSex: '', // '性别',
        contactEthnic: '', // '民族',
        contactIssuing: '', // '签发机关',
        contactBirth: '', // '出生日期',
        contactCardStart: '', // '证件起始日期',
        contactCardEnd: '', // '证件到期日期',
        longEffect: false, // 长期有效,
        contactAddress: '', // '户籍地址',
        contactPhone: '', // '手机号码',
        contactEmail: '', // '邮箱',
        contactRPic: '', // '身份证人像面',
        contactBPic: '', // '身份证国徽面',
        status: '', // 运营人员状态
        privilegeYl: [], // 数信易链
        privilegeYr: [], // 数信易融
      },
      rules: {
        contactName: [{ required: true, trigger: ['change', 'blur'], message: '请输入联系人姓名' }], // 联系人姓名
        contactType: [{ required: true, trigger: ['change', 'blur'], message: '请输入证件类型' }], // '证件类型',
        contactId: [
          { required: true, trigger: ['change', 'blur'], message: '请输入身份证号' },
          {
            validator: (rule, value, callback) => {
              if (/(^\d{15}$)|(^\d{17}(\d|X)$)/.test(value)) {
                callback();
              } else {
                callback('请输入正确的身份证号');
              }
            },
            trigger: ['change', 'blur'],
          }
        ], // '身份证号',
        contactSex: [{ required: true, trigger: ['change', 'blur'], message: '请输入性别' }], // '性别',
        contactEthnic: [{ required: true, trigger: ['change', 'blur'], message: '请输入民族' }], // '民族',
        contactIssuing: [{ required: true, trigger: ['change', 'blur'], message: '请输入签发机关' }], // '签发机关',
        contactBirth: [{ required: true, trigger: ['change', 'blur'], message: '请输入出生日期' }], // '出生日期',
        contactCardStart: [{ required: true, trigger: ['change', 'blur'], message: '请输入证件起始日期' }], // '证件起始日期',
        contactCardEnd: [{ required: true, trigger: ['change', 'blur'], message: '请输入证件到期日期' }], // '证件到期日期',
        longEffect: [{ required: true, trigger: ['change', 'blur'], message: '请输入证件到期日' }], // 长期有效
        contactAddress: [{ required: true, trigger: ['change', 'blur'], message: '请输入户籍地址' }], // '户籍地址',
        contactPhone: [
          { required: true, trigger: ['change', 'blur'], message: '请输入手机号码' },
          {
            validator: (rule, value, callback) => {
              if (/^1\d{10}$/.test(value)) {
                callback();
              } else {
                callback('请输入正确的手机号');
              }
            },
            trigger: ['change', 'blur']
          }
        ], // '手机号码',
        contactEmail: [
          { required: true, trigger: ['change', 'blur'], message: '请输入邮箱' },
          {
            validator: (rule, value, callback) => {
              if (/^([a-zA-Z0-9_.+-]+)@[a-zA-Z0-9.-]+\.([a-zA-Z]{2,})$/.test(value)) {
                callback();
              } else {
                callback('请输入正确的邮箱');
              }
            },
            trigger: ['change', 'blur']
          }
        ], // '邮箱',
        contactRPic: [{ required: true, trigger: ['change', 'blur'], message: '请上传身份证人像面' }], // '身份证人像面',
        contactBPic: [{ required: true, trigger: ['change', 'blur'], message: '请上传身份证国徽面' }], // '身份证国徽面',
        status: [{ required: true, trigger: ['change', 'blur'], message: '请选择运营人员状态' }], // 运营人员状态
        // privilegeYl: [{ type: 'array', required: true, trigger: ['change', 'blur'], message: '请勾选数信易链' }], // 数信易链
        // privilegeYr: [{ type: 'array', required: true, trigger: ['change', 'blur'], message: '请输勾选数信易融' }], // 数信易融
      },
      contactRPicError: "", // 身份证人像面,图片校验错误提示语
      contactBPicError: "", // 身份证国徽面,图片校验错误提示语
      previewBigImgUrl: "", // 预览图
      dialogVisible: false, // 预览图
      userId: '',
      detailObj: {},
    };
  },
  mounted() {
    Promise.all([
      this.getIdTypeList(),
      this.getSexList(),
      this.getOperationStatus(),
    ]).then(() => {
      if (this.$route.query.userId) {
        this.userId = this.$route.query.userId
        this.getOperationDetail()
      }
    })
  },
  methods: {
    // 证件类型列表
    getIdTypeList() {
      return new Promise((resolve, reject) => {
        this.getDicts('id_type_list').then((res) => {
          this.idTypeList = res.data
          resolve()
        }).catch(() => {
          reject()
        })
      })
    },
    // 性别列表
    getSexList() {
      return new Promise((resolve, reject) => {
        this.getDicts('sex_list').then((res) => {
          this.sexList = res.data
          resolve()
        }).catch(() => {
          reject()
        })
      })
    },
    // 获取运人员状态
    getOperationStatus() {
      return new Promise((resolve, reject) => {
        this.getDicts('operationstatus').then((res) => {
          this.statusList = res.data
          resolve()
        }).catch(() => {
          reject()
        })
      })
    },
    getOperationDetail() {
      operationDetail(this.userId).then((res) => {
        this.detailObj = res.data
        Object.keys(this.form).forEach((key) => {
          this.form[key] = res.data[key]
        })
        if (this.form.contactCardEnd === '1') {
          this.form.longEffect = true
        } else {
          this.form.longEffect = false
        }
        this.form.privilegeYl = res.data.privilegeYl?.split(',') || []
        this.form.privilegeYr = res.data.privilegeYr?.split(',') || []
        console.log(this.form)
      })
    },
    // 图片上传校验
    imgValidate(fileType, fileSize, name, types = 'image/jpeg,image/jpg,image/png') {
      if (types.indexOf(fileType.split('/')[1]) === -1) {
        this[name] = '上传格式不正确'
        return false
      }
      if (fileSize/1000/1024 > 10) {
        this[name] = '大小不超过10M'
        return false
      }
      return true
    },
    // 身份证ocr 正面
    ocrIdCardFront(e) {
      const file = e.target.files[0]
      e.target.value = ''
      if (!this.imgValidate(file.type, file.size, 'businessPicError')) {
        return
      }
      this.contactRPicLoading = true
      uploadImg('/ocrIdCard', { type: 'front', file }).then((res) => {
        this.contactRPicLoading = false
        this.form.contactAddress = res.data.idcard.address
        this.form.contactBirth = res.data.idcard.birth
        this.form.contactId = res.data.idcard.cardId
        this.form.contactName = res.data.idcard.name
        this.form.contactEthnic = res.data.idcard.nation
        this.form.contactSex = res.data.idcard.sex === '1' ?  '男' : '女' // 1: 男 2: 女
        this.form.contactRPic = res.data.url
      }).catch(() => {
        this.contactRPicLoading = false
      })
    },
    // 法人 身份证——正面 图片删除
    deleteContactRPic() {
      this.idCardFrontObjOfFaRen = {};
      [
        'contactAddress', 'contactBirth', 'contactId',
        'contactName', 'contactEthnic', 'contactSex',
        'contactRPic'
      ].forEach(key =>  {
        this.form[key] = ''
      })
    },
    // 身份证orc 反面
    ocrIdCardBack(e) {
      const file = e.target.files[0]
      e.target.value = ''
      if (!this.imgValidate(file.type, file.size, 'businessPicError')) {
        return
      }
      this.contactBPicLoading = true
      uploadImg('/ocrIdCard', { type: 'back', file }).then((res) => {
        this.contactBPicLoading = false
        if (res.data.idcard.idcardPeriodEnd === '1') {
          this.form.longEffect = true
        } else {
          this.form.contactCardEnd = res.data.idcard.idcardPeriodEnd
        }
        this.form.contactCardStart = res.data.idcard.idcardPeriodStart
        this.form.contactIssuing = res.data.idcard.issuing
        this.form.contactBPic = res.data.url
      }).catch(() => {
        this.contactBPicLoading = false
      })
    },
    // 法人 身份证——反面 图片删除
    deleteContactBPic() {
      this.idCardBackObjOfFaRen = {};
      [
        'contactCardEnd', 'longEffect', 'contactCardStart', 'contactIssuing',
        'contactBPic'
      ].forEach(key =>  {
        if (key === 'longEffect') {
          this.form[key] = false
        } else {
          this.form[key] = ''
        }
      })
    },
    // 预览上传的大图
    previewBigImg(imgUrl) {
      this.previewBigImgUrl = imgUrl;
      this.dialogVisible = true;
    },
    // 取消
    cancelFn() {
      this.$router.back();
    },
    // 确定
    submit() {
      const { privilegeYl, privilegeYr, contactCardEnd, longEffect, ...rest} = this.form
      const data = {
        ...( this.userId ? this.detailObj : {}),
        ...(longEffect === true ? { contactCardEnd: '1' } : { contactCardEnd }),
        ...rest,
        privilegeYl: this.form.privilegeYl.join(','),
        privilegeYr: this.form.privilegeYr.join(','),
      }
      console.log(data)
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.form.privilegeYl.length === 0 && this.form.privilegeYr.length === 0) {
            this.$message({
              type: 'error',
              message: '数信易融和数信易链至少勾选一个分配权限'
            })
            return
          }
          let result
          this.submitLoading = true
          if (this.userId) {
            result = editOperation(data)
          } else {
            result = addOperation(data)
          }
          result.then(() => {
            this.submitLoading = false
            this.$message({
              type: 'success',
              message: '提交成功',
              onClose: () => {
                this.$router.back()
              }
            })
          }).catch(() => {
            this.submitLoading = false
          })
        } else {
          this.$message({
            type: 'error',
            message: '有信息未填'
          })
        }
      })
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/assets/styles/variables.scss";

.add_operational_people_page {
  .mod {
    border-radius: 6px;
    box-shadow: 0 1px 2px 0 rgba(1, 24, 70, 0.09);
    background-color: #fff;
    margin-bottom: 16px;
    padding: 20px 0;
    &:last-child {
      margin-bottom: 0;
    }
    .title {
      color: #333;
      font-size: 16px;
      font-weight: 600;
      display: flex;
      align-items: center;
      padding-left: 16px;
      .icon {
        display: block;
        width: 3px;
        height: 16px;
        background-color: $theme;
        margin-right: 5px;
      }
    }
    .content {
      padding: 40px 140px 0 0;
      ::v-deep .el-form-item.el-form-item--medium {
        margin-bottom: 20px;
      }
      ::v-deep .el-form-item--medium .el-form-item__label {
        width: 206px;
        font-size: 14px;
        color: #777;
      }
      ::v-deep .el-form-item--medium .el-form-item__content {
        margin-left: 206px;
      }
      .upload_box {
        margin-bottom: 20px;
        margin-left: 120px;
        display: flex;
        ::v-deep .el-form-item {
          margin-bottom: 0;
        }
        .ID_top,
        .ID_back {
          width: 340px;
          height: 214px;
          border-radius:5px;
          margin-right: 40px;
          position: relative;
          .upload_input {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            z-index: 2;
            opacity: 0;
          }
          .img {
            display: block;
            width: 100%;
            height: 100%;
          }
          .mask {
            display: none;
          }
          &:hover {
            .mask {
              display: block;
              position: absolute;
              top: 0;
              left: 0;
              right: 0;
              bottom: 0;
              z-index: 2;
              background-color: rgba(0, 0, 0, 0.5);
              display: flex;
              justify-content: space-evenly;
              align-items: center;
              color: #fff;
              font-size: 30px;
              font-weight: 600;
              .preview,
              .delete {
                cursor: pointer;
              }
            }
          }
        }
        .ID_top {
          margin-right:30px;
          background: #e0f0ff url("../../../assets/authenticate/ID.jpg")
            no-repeat 0 0;
          background-size: 100% 100%;
          &:hover {
            background: url("../../../assets/authenticate/ID_hover.jpg")
              no-repeat 0 0;
            background-size: 100% 100%;
          }
        }
        .ID_back {
          margin-right: 44px;
          background: #e0f0ff url("../../../assets/authenticate/ID_back.jpg")
            no-repeat 0 0;
          background-size: 100% 100%;
          &:hover {
            background: #e0f0ff
              url("../../../assets/authenticate/ID_back_hover.jpg") no-repeat 0 0;
            background-size: 100% 100%;
          }
        }
        .desc_box {
          padding-top: 24px;
          .desc_name {
            color: #333;
            font-size: 14px;
            font-weight: 600;
            margin-bottom: 12px;
          }
          .desc_text {
            color: #555;
            font-size: 16px;
            line-height: 28px;
          }
        }
      }
      .tips {
        height: 32px;
        line-height: 32px;
        color: #f29c1c;
        font-size: 13px;
        background-color: #fffaf4;
        border-radius: 2px;
        padding: 0 16px;
        display: flex;
        align-items: center;
        margin-left: 120px;
        margin-bottom: 30px;
        .icon {
          font-size: 14px;
          color: #f29c1c;
          margin-right: 8px;
        }
      }
      .msg_box {

      }
      .long_effect_line {
        display: flex;
        align-items: center;
        .long_effect {
          margin-left: 24px;
        }
      }
    }
  }
  .btns {
    display: flex;
    justify-content: center;
    align-items: center;
    .btn {
      width: 120px;
    }
    .btn_sure {
      margin-left: 40px;
    }
  }
}
</style>
